package org.blame.lotterysystem.service.impl;


import org.blame.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import org.blame.lotterysystem.common.exception.ServiceException;
import org.blame.lotterysystem.common.utils.*;
import org.blame.lotterysystem.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    private static final String VERIFICATION_CODE_PREFIX="VERIFICA`TION_CODE_";
    private static final Long VERIFICATION_CODE_TIMEOUT=60L;
    private static final String VERIFICATION_CODE_TEMPLATE_CODE="SMS_465324787";

    @Autowired
    private CaptchaUtil captchaUtil;

    @Autowired
    private SMSUtil smsUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void setVerificationCode(String phoneNumber) {
//        校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
//        生成随机验证码
        String captcha =captchaUtil.getCaptcha(6);
        System.out.println("手机号 " + phoneNumber + " 的验证码是: " + captcha);

//      因为个人无法目前发送验证码，所以使用随机数来代替
//        发送验证码
//        Map<String,String> map=new HashMap<>();
//        map.put("code",captcha);
//        smsUtil.sendMessage(VERIFICATION_CODE_TEMPLATE_CODE,
//                phoneNumber,
//                JacksonUtil.writeValueAsString(map));

//        将验证码存入到redis中
        redisUtil.set(VERIFICATION_CODE_PREFIX+phoneNumber,captcha,VERIFICATION_CODE_TIMEOUT);

    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        //        校验手机号
        if (!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }

//        从缓存中拿出验证码
        return redisUtil.get(VERIFICATION_CODE_PREFIX+phoneNumber);
    }
}
